<template>
  <a-card title="修改配置">
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 7, sm: 24 } : { flex: '90px' }"
      :wrapper-col="styleResponsive ? { md: 17, sm: 24 } : { flex: '1' }"
    >
      <a-row :gutter="16">
        <a-col
          v-bind="styleResponsive ? { md: 12, sm: 24, xs: 24 } : { span: 12 }"
        >
          <a-form-item label="上级栏目" name="parentId">
            <cate-select
              :data="cateList"
              placeholder="请选择上级栏目"
              v-model:value="form.parentId"
            />
          </a-form-item>
          <a-form-item label="栏目名称" name="cateName">
            <a-input
              allow-clear
              :maxlength="20"
              placeholder="请输入栏目名称"
              v-model:value="form.cateName"
            />
          </a-form-item>
          <a-form-item label="主题颜色">
            <ele-color-picker
              :show-alpha="true"
              v-model:value="form.color"
              :predefine="predefineColors"
            />
          </a-form-item>
          <a-form-item label="栏目图片">
            <ele-image-upload
              v-model:value="images"
              :limit="1"
              :drag="true"
              :upload-handler="uploadHandler"
              :remove-handler="removeHandler"
              @upload="onUpload"
            />
          </a-form-item>
        </a-col>
        <a-col
          v-bind="styleResponsive ? { md: 12, sm: 24, xs: 24 } : { span: 12 }"
        >
          <a-form-item label="栏目类型" name="menuType">
            <a-radio-group
              v-model:value="form.menuType"
              @change="onMenuTypeChange"
            >
              <a-radio :value="0">目录</a-radio>
              <a-radio :value="1">菜单</a-radio>
              <a-radio :value="2">外链</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="外链地址" name="url" v-if="form.menuType === 2">
            <a-input
              allow-clear
              placeholder="请输入外链地址"
              v-model:value="form.url"
            />
          </a-form-item>
          <a-form-item
            label="栏目模板"
            name="template"
            v-if="form.menuType !== 2"
          >
            <a-input
              allow-clear
              placeholder="请输入栏目模板"
              :disabled="form.menuType === 0"
              v-model:value="form.template"
            />
          </a-form-item>
          <a-form-item label="排序号" name="sortNumber">
            <a-input-number
              :min="0"
              :max="99999"
              class="ele-fluid"
              placeholder="请输入排序号"
              v-model:value="form.sortNumber"
            />
          </a-form-item>
          <a-form-item label="描述">
            <a-textarea
              :rows="4"
              :maxlength="200"
              placeholder="请输入描述"
              v-model:value="form.introduction"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row justify="end">
        <a-col :span="3">
          <a-form-item :wrapper-col="{ flex: 1 }" justify="end">
            <a-button type="primary" @click="save">提交</a-button>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-card>
</template>
<script lang="ts" setup>
  import { Category } from '@/api/content/category/model';
  import { useThemeStore } from '@/store/modules/theme';
  import useFormData from '@/utils/use-form-data';
  import { message } from 'ant-design-vue/es';
  import type { FormInstance, Rule } from 'ant-design-vue/es/form';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { storeToRefs } from 'pinia';
  import CateSelect from './cate-select.vue';
  import { reactive, ref, watch } from 'vue';
  import request from '@/utils/request';
  import { getCategory, updateCategory } from '@/api/content/category';

  const props = defineProps<{
    // 栏目 id
    cateId?: number;
    // 全部栏目
    cateList: Category[];
  }>();
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);
  const formRef = ref<FormInstance | null>(null);
  const images = ref<ItemType[]>([]);
  // 提交状态
  const loading = ref(false);
  // 表单数据
  const { form } = useFormData<Category>({
    cateId: undefined,
    parentId: undefined,
    cateName: '',
    menuType: 0,
    url: '',
    template: '',
    color: 'rgba(255, 69, 0, 0.68)',
    image: '',
    sortNumber: undefined,
    introduction: ''
  });
  // 预设颜色
  const predefineColors = ref([
    '#ff4500',
    '#ff8c00',
    '#ffd700',
    '#90ee90',
    '#00ced1',
    '#1e90ff',
    '#c71585',
    'rgba(255, 69, 0, 0.68)',
    'rgb(255, 120, 0)',
    'hsv(51, 100, 98)',
    'hsva(120, 40, 94, 0.5)',
    'hsl(181, 100%, 37%)',
    'hsla(209, 100%, 56%, 0.73)',
    '#c7158577'
  ]);
  // 表单验证规则
  const rules = reactive<Record<string, Rule[]>>({
    cateName: [
      {
        required: true,
        message: '请输入栏目名称',
        type: 'string',
        trigger: 'blur'
      }
    ],
    sortNumber: [
      {
        required: true,
        message: '请输入排序号',
        type: 'number',
        trigger: 'blur'
      }
    ]
  });
  /* menuType选择改变 */
  const onMenuTypeChange = () => {
    if (form.menuType === 0) {
      form.url = '';
      form.template = '';
    } else if (form.menuType === 1) {
      form.url = '';
    } else {
      form.template = '';
    }
  };
  /* 上传事件 */
  const uploadHandler = (file: File) => {
    const item: ItemType = {
      file,
      uid: (file as any).uid,
      name: file.name,
      progress: 0,
      status: undefined
    };
    if (!file.type.startsWith('image')) {
      message.error('只能选择图片');
      return;
    }
    if (file.size / 1024 / 1024 > 2) {
      message.error('大小不能超过 2MB');
      return;
    }
    item.url = window.URL.createObjectURL(file);
    images.value.push(item);
    onUpload(item);
  };

  const removeHandler = (item) => {
    images.value = images.value.filter((d) => d !== item);
  };

  /* 上传 item */
  const onUpload = (d: ItemType) => {
    const item: any = images.value.find((t) => t.uid === d.uid) ?? d;
    // 上传
    item.status = 'uploading';
    const formData = new FormData();
    formData.append('file', item.file);
    request({
      url: '/file/upload',
      method: 'post',
      data: formData,
      onUploadProgress: (e: any) => {
        // 文件上传进度回调
        if (e.lengthComputable) {
          item.progress = (e.loaded / e.total) * 100;
        }
      }
    })
      .then((res) => {
        if (res.data.code === 0) {
          item.status = 'done';
          item.url = res.data.data;
        }
      })
      .catch((e) => {
        message.error(e);
        item.status = 'exception';
      });
  };
  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const cateData = {
          ...form,
          parentId: form.parentId || 0,
          image: images.value.length !== 0 ? images.value[0].url : undefined
        };
        updateCategory(cateData)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };
  const getCateDetail = (cateId) => {
    images.value = [];
    getCategory(cateId).then((res: any) => {
      Object.assign(form, res);
      if (res.image) {
        images.value.push({
          url: res.image,
          uid: ''
        });
      }
    });
  };
  getCateDetail(props.cateId);
  watch(
    () => props.cateId,
    (value) => {
      if (value) {
        getCateDetail(value);
      }
    }
  );
</script>
<style lang="scss" scoped></style>
